package nciae.db.controller;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import com.lowagie.text.*;
import com.lowagie.text.pdf.BaseFont;
import com.lowagie.text.pdf.PdfWriter;
import com.lowagie.text.pdf.draw.LineSeparator;
import nciae.db.common.CommonResult;
import org.apache.commons.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import nciae.db.pojo.entity.Course;
import nciae.db.service.CourseService;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.OutputStream;
import java.lang.annotation.Documented;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.Map;

@RestController
public class QRCodeController {

    @Autowired
    private CourseService courseService;

    private static final int QR_CODE_SIZE = 400;  // 二维码的尺寸

    @GetMapping("/generate-qr-code")
    public CommonResult generateQRCode(@RequestParam Integer courseId) {
        CommonResult<Object> result = new CommonResult<>();
        // 获取课程信息
        Course course = courseService.getById(courseId);
        if (course == null) {
            result.setCode(-1);
            result.setMsg("Course not found!");
            return result;
        }

        try {
            // 生成二维码内容，结合课程 ID、上课日期和当前时间戳
            String qrCodeContent = "courseId=" + courseId + "&lessonDate=" + course.getLessonDate() + "&timestamp=" + System.currentTimeMillis();

            // 使用 ZXing 库生成二维码
            Map<EncodeHintType, Object> hints = new HashMap<>();
            hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
            MultiFormatWriter writer = new MultiFormatWriter();
            BitMatrix matrix = writer.encode(qrCodeContent, BarcodeFormat.QR_CODE, QR_CODE_SIZE, QR_CODE_SIZE, hints);

            // 将二维码转为 Base64 编码的图片
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            ImageIO.write(toBufferedImage(matrix), "PNG", byteArrayOutputStream);
            String base64QRCode = Base64.encodeBase64String(byteArrayOutputStream.toByteArray());

            // 保存二维码内容到数据库（保存原始信息）
            course.setQrCode(qrCodeContent);  // 存储二维码内容（非图像）
            courseService.updateById(course);  // 更新数据库中的二维码信息
            result.setData(base64QRCode);  // 将二维码图像返回给前端
            result.setCode(0);
            return result;
        } catch (Exception e) {
            result.setCode(-1);
            result.setMsg("Error generating QR code!");
            return result;
        }
    }

    @GetMapping("/printQRCode/{courseId}")
    public void printQRCode(@PathVariable("courseId") Integer id, HttpServletResponse response) {
        // 获取课程信息
        System.out.println(id);
        Course course = courseService.getById(id);
        System.out.println(course.getAddress());
        try {
            response.setContentType("application/pdf");
            response.setHeader("Content-Disposition", "attachment;filename=printQRCode.pdf");
            OutputStream outputStream = response.getOutputStream();

            // 生成二维码内容，结合课程 ID、上课日期和当前时间戳
            String qrCodeContent = "courseId=" + id + "&lessonDate=" + course.getLessonDate() + "&timestamp=" + System.currentTimeMillis();

            // 创建文档实例
            Document document = new Document(PageSize.A4, 50, 50, 50, 50); // 设置页面大小和边距

            // 使用 PdfWriter 将文档绑定到输出流
            PdfWriter.getInstance(document, outputStream);

            // 打开文档
            document.open();

            // 加载中文字体 (宋体)
            BaseFont baseFont = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
            // 正文字体
            Font contentFont = new Font(baseFont, 12, Font.NORMAL);
//            // 标题字体
//            Font titleFont = new Font(baseFont, 18, Font.BOLD);
            // 小标题字体
            Font subTitleFont = new Font(baseFont, 14, Font.BOLD);
//            // 课程信息标题
//            Paragraph title = new Paragraph("课程信息", titleFont);
//            title.setAlignment(Element.ALIGN_CENTER);
//            document.add(title);
//            // 添加分割线
//            document.add(new Paragraph(new Chunk(new LineSeparator())));

            // 格式化日期
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            String formattedDate = dateFormat.format(course.getLessonDate());

            // 生成二维码
            QRCodeWriter qrCodeWriter = new QRCodeWriter();
            BitMatrix bitMatrix = qrCodeWriter.encode(qrCodeContent, BarcodeFormat.QR_CODE, 400, 400);
            BufferedImage qrImage = toBufferedImage(bitMatrix);

            // 将二维码添加到PDF并居中
            Image qrCodeImage = Image.getInstance(qrImage, null);
            qrCodeImage.setAlignment(Element.ALIGN_CENTER);
            document.add(qrCodeImage);

//            // 添加格式化后的日期
//            document.add(new Paragraph("课程: " + course.getSubject(), contentFont));
//            document.add(new Paragraph("内容要点: " + course.getContent(), contentFont));
//            document.add(new Paragraph("地点: " + course.getAddress(), contentFont));
//            document.add(new Paragraph("日期: " + formattedDate, contentFont));
//            document.add(new Paragraph("时间段: " + course.getTimeSpan(), contentFont));
//            document.add(new Paragraph("教师: " + course.getTeacher(), contentFont));
//// 添加分割线
//            document.add(new Paragraph(new Chunk(new LineSeparator())));

////            // 课程详细信息小标题
////            Paragraph subTitle = new Paragraph("课程信息", subTitleFont);
//            subTitle.setAlignment(Element.ALIGN_CENTER);
//            document.add(subTitle);
            // 添加课程详细信息段落
            addCourseInfoParagraph(document, "课程", course.getSubject(), contentFont);
            addCourseInfoParagraph(document, "内容要点", course.getContent(), contentFont);
            addCourseInfoParagraph(document, "地点", course.getAddress(), contentFont);
            addCourseInfoParagraph(document, "日期", formattedDate, contentFont);
            addCourseInfoParagraph(document, "时间段", course.getTimeSpan(), contentFont);
            addCourseInfoParagraph(document, "教师", course.getTeacher(), contentFont);

            document.close();
            System.out.println("PDF 生成成功");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 辅助方法：添加课程信息段落
    private void addCourseInfoParagraph(Document document, String label, String value, Font font) throws DocumentException {
        Paragraph paragraph = new Paragraph(label + ": " + value, font);
        paragraph.setAlignment(Element.ALIGN_LEFT);
        paragraph.setSpacingAfter(5); // 设置段落间距
        document.add(paragraph);
    }


    // 将 BitMatrix 转换为 BufferedImage
    private BufferedImage toBufferedImage(BitMatrix matrix) {
        int width = matrix.getWidth();
        int height = matrix.getHeight();
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        image.createGraphics();
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                image.setRGB(x, y, matrix.get(x, y) ? 0x000000 : 0xFFFFFF);  // 黑白色
            }
        }
        return image;
    }

}
